#!/usr/bin/env python
# -*- coding: utf8 -*-

'''
# created by: iori
# created on: Tue 03 Dec 2013 02:05:25 PM CST
将一个 ass格式的字幕文件转换成srt格式的字幕文件
'''
import os, sys
import re
import codecs
def ass2srt(path):
    new_path = os.path.splitext(path)[0] + '.srt'
    print 'convert', path
    # because ass use utf16 encode to save file, we use codecs module to load it, and
    # all data are now unicode.
    with codecs.open(path, 'rb', 'utf16') as fin, open(new_path, 'wb') as fout:
        index = 0
        for line in fin:
            line = line.strip().encode('utf8') # convert it to utf8
            if line.startswith('Dialogue:'):
                fout.write('{}\n'.format(index))
                index += 1
                line = re.sub(r'{.*?}', '', line)
                entries = line.strip().split(',', 9) # at most seperate 9 times, 10 item.
                fout.write('{0}0 --> {1}0\n'.format(entries[1].replace('.', ','), entries[2].replace('.',',')))
                fout.write('{}\n\n'.format(entries[9].replace('\\N', '\n')))


def ass_to_srt(paths):
    if isinstance(paths, (str, unicode)):
        paths = [paths]
    for path in paths:
        ass2srt(path)


def main(paths):
    for path in paths:
        ass2srt(path)


if __name__ == '__main__':
    main(sys.argv[1:])

